package com.cherrish.demo;

import java.util.LinkedHashMap;
import java.util.concurrent.*;

/**
 * @author cherrish
 * @time 2019-04-17 17:53
 * @name TestFuture
 * @desc:
 */
public class TestFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testFuture();

        testCompletableFuture();

        testCompletableFuture1();
        testCompletableFuture2();
    }

    private static void testCompletableFuture2() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            return 10;
        });
        future.thenAccept(System.out::println);

    }

    private static void testCompletableFuture1() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            return 10;
        });
        CompletableFuture<String> f = future.thenApply(i ->i+1 ).thenApply(i-> String.valueOf(i));
        System.out.println(f.get());
    }

    private static void testCompletableFuture(){
        /*CompletableFuture<String> completableFuture = new CompletableFuture<>();
        new Thread(()->{
            completableFuture.completeExceptionally(new RuntimeException("error"));
            completableFuture.complete(Thread.currentThread().getName());
        }).start();*/

        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            return Thread.currentThread().getName();
        });

        doSomething();

        try {
            System.out.println(completableFuture.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static void testFuture(){
        ExecutorService executors = Executors.newSingleThreadExecutor();

        Future<String> future = executors.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Thread.currentThread().getName();
            }
        });

        doSomething();

        try {
            String result = future.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static void doSomething(){
        System.out.println("Test Future -------> 00000000");
    }
}
